package com.jwm.platform;

import com.jwm.model.*;
import com.jwm.platform.db.Schedule;
import com.jwm.platform.db.ScheduleVo;
import com.jwm.model.ServiceVo;
import com.jwm.util.DateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.scheduling.support.PeriodicTrigger;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author 崔洁
 */
@Component
@EnableScheduling
public class PlatformTimeTask implements SchedulingConfigurer {
    private static final Logger logger = LoggerFactory.getLogger(PlatformTimeTask.class);
    @Resource
    private PlteData heartData;
    @Resource
    private PlatformConfig platformConfig;
    @Resource
    private Schedule schedule;
    @Resource
    private PlatController platController;

    @Override
    public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
        if (platformConfig.getTimeInterval() > 0) {
            taskRegistrar.addTriggerTask(
                    () -> {
                        logger.info("平台端 => 刷新状态执行-开始");
                        for (ClientVo clientVo : heartData.getClientVoList()) {
                            if (clientVo.getState() == 1 && Double.parseDouble(DateUtils.dateTimeNow()) - Double.parseDouble(clientVo.getTime()) > platformConfig.getClientTimeout()) {
                                clientVo.setState(0);
                            }
                            for (TomcatVo tomcatVo : clientVo.getTomcatVos()) {
                                if (tomcatVo.getState() == 1 && Double.parseDouble(DateUtils.dateTimeNow()) - Double.parseDouble(tomcatVo.getTime()) > platformConfig.getClientTimeout()) {
                                    tomcatVo.setState(0);
                                }
                            }
                            for (JarVo jarVo : clientVo.getJarVos()) {
                                if (jarVo.getState() == 1 && Double.parseDouble(DateUtils.dateTimeNow()) - Double.parseDouble(jarVo.getTime()) > platformConfig.getClientTimeout()) {
                                    jarVo.setState(0);
                                }
                            }
                            for (ServiceVo serviceVo : clientVo.getServiceVos()) {
                                if (serviceVo.getState().equals("运行中") && Double.parseDouble(DateUtils.dateTimeNow()) - Double.parseDouble(serviceVo.getTime()) > platformConfig.getClientTimeout()) {
                                    serviceVo.setState("停止中");
                                }
                            }
                            for (BatVo batVo : clientVo.getBatVos()) {
                                if (batVo.getState().equals("运行中") && Double.parseDouble(DateUtils.dateTimeNow()) - Double.parseDouble(batVo.getTime()) > platformConfig.getClientTimeout()) {
                                    batVo.setState("停止中");
                                }
                            }
                        }
                        logger.info("平台端 => 刷新状态执行-结束");
                    },
                    //triggerContext -> new CronTrigger("0/" + platformConfig.getTimeInterval() + " * * * * ?").nextExecutionTime(triggerContext)
                    triggerContext -> new PeriodicTrigger(platformConfig.getTimeInterval()).nextExecutionTime(triggerContext)
            );
        }
    }

    @Scheduled(cron = "0 0/10 * * * ?")
    public void autoTask() {
        if (platformConfig == null) {
            return;
        }
        Date date = new Date();
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        SimpleDateFormat df1 = new SimpleDateFormat("yyyy");
        SimpleDateFormat df2 = new SimpleDateFormat("yyyy-MM");
        SimpleDateFormat df3 = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat df4 = new SimpleDateFormat("yyyy-MM-dd HH");
        Calendar nowMinute = Calendar.getInstance();
        nowMinute.setTime(new Date());
        nowMinute.add(Calendar.SECOND, 30);
        String dd = df.format(nowMinute.getTime());
        // 匹配定时任务
        List<ScheduleVo> list = (List<ScheduleVo>) schedule.list().get("data");
        List<ScheduleVo> collect = list.stream().filter(scheduleVo -> scheduleVo.getEnable() > 0).collect(Collectors.toList());
        System.out.println("==========" + dd + ",执行定时任务,全部数量：" + collect.size() + "。==========");
        for (ScheduleVo scheduleVo : collect) {
            CmdInfoVo cmdInfoVo = new CmdInfoVo();
            cmdInfoVo.setClientName(scheduleVo.getClient());
            cmdInfoVo.setServerName(scheduleVo.getServer());
            cmdInfoVo.setTypeEnum(TypeEnum.valueOfLabel(scheduleVo.getType()));
            cmdInfoVo.setCmdEnum(CmdEnum.valueOfLabel(scheduleVo.getCmd()));
            String d = scheduleVo.getDatetime();
            String dd1 = df1.format(date) + "-" + d;
            String dd2 = df2.format(date) + "-" + d;
            String dd3 = df3.format(date) + " " + d;
            String dd4 = df4.format(date) + ":" + d;
            if (dd.equals(dd1)) {
                // 匹配到每年
                platController.cmd(cmdInfoVo);
            } else if (dd.equals(dd2)) {
                // 匹配到每月
                platController.cmd(cmdInfoVo);
            } else if (dd.equals(dd3)) {
                // 匹配到每天
                platController.cmd(cmdInfoVo);
            } else if (dd.equals(dd4)) {
                // 匹配到每小时
                platController.cmd(cmdInfoVo);
            } else {
                // 匹配到每十分钟
                platController.cmd(cmdInfoVo);
            }
        }
    }
}
